var FilePath=require("../file-path.js")
var Util = require(FilePath.ModulesPath+'util')
const dgram = require('dgram');
var LogDB=require(FilePath.ModulesPath+'db').LOG_DB

class UdpMode{
    constructor(ip,port,targetIP,targetPort,RevCb=null){
        this.config_IP=ip;
        this.config_port=port;
        this.target_IP=targetIP;
        this.target_port=targetPort;
        this.RevCb = RevCb;
        this.rev_data=[];
        this.IsRev = false;
        UdpMode.upd_client=null;  //TODO 静态后期可能会有问题
    }
    SendData(buf_data){
        if((!UdpMode.upd_client)||(!this.target_IP)){
            return;
        }
        this.rev_data=[];
        UdpMode.upd_client.send(buf_data, this.target_port,this.target_IP)
    }
    async AsyncRecvData(timeout=300){//tmout=0-收到一包数据返回。timout！=0 等待固定时间的数据
        this.IsRev = true;
        if(timeout!=0){
            await Util.Delay(timeout);
        }else {
            while (timeout > 0){
                timeout -= 20;
                if(this.rev_data.length > 0 ){
                    this.IsRev = false;
                    return this.rev_data.pop(0);
                }
                await Util.Delay(20);
            }
        }
        this.IsRev = false;
        return this.rev_data;
    }
    Start(){
        if(UdpMode.upd_client){
            return;
        }
        UdpMode.upd_client=dgram.createSocket('udp4');
        UdpMode.upd_client.on('error', (err) => {
            console.log(`udp error：\n${err.stack}`);
            LogDB.AsyncInsert(err.toString());
            UdpMode.upd_client.close();
            UdpMode.upd_client=null;
        });
        UdpMode.upd_client.on('message', (buffer, rinfo) => {
            // console.log(`udp receive: ${rinfo.address}:${rinfo.port} data:`,  buffer);
            if(this.RevCb){
                this.RevCb(buffer,rinfo);
            }else{
                if(this.IsRev){
                    this.rev_data.push(buffer);
                }
            }
        });
        UdpMode.upd_client.on('listening', () => {
            const address = UdpMode.upd_client.address();
            console.log(`udp listening ${address.address}:${address.port}`);
        });
        UdpMode.upd_client.bind(this.config_port,this.config_IP);
    }

}
exports.UdpMode=UdpMode;